<style lang="less" scoped>
.filter-blk {
  /deep/.el-form-item {
    width: 23% !important;
    .el-form-item__content {
      width: 60% !important;
    }
  }
}
</style>
<template>
  <el-container :style="{ height: winH - 160 + 'px' }">
    <el-aside class="area-blk" width="250px">
      <h2 class="hd">分区列表（右键编辑）</h2>
      <partitionTree
        :businessId="businessId"
        :isEditable="true"
        @nodeClick="partitionClickAction"
      ></partitionTree>
    </el-aside>
    <el-main class="census-main">
      <div class="opers flex v-c">
        <el-form :inline="true" class="filter-blk flex-1">
          <el-form-item label="设备名称">
            <el-input
              placeholder="请输入设备名称"
              v-model.trim="filterForm.name"
            ></el-input>
          </el-form-item>
          <el-form-item label="设备编号">
            <el-input
              placeholder="请输入设备编号"
              v-model.trim="filterForm.number"
            ></el-input>
          </el-form-item>
          <el-form-item label="设备类型">
            <el-select
              v-model="filterForm.deviceTypeId"
              placeholder="请选择"
              clearable
            >
              <el-option
                :label="item.name"
                :value="item.id"
                v-for="(item, key) in typeList"
                :key="key"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="检修状态">
            <el-select
              v-model="filterForm.state"
              placeholder="请选择"
              clearable
            >
              <el-option label="已检测" value="1"></el-option>
              <el-option label="未检测" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-button type="primary" @click="searchAction"
          ><i class="iconfont icon-search"></i> 搜索</el-button
        >
        <el-button type="primary" @click="resetAction"
          ><i class="iconfont icon-refresh"></i> 重置</el-button
        >
        <el-button
          type="primary"
          @click="recoveryStatus"
          :disabled="!activePartition || activePartition.id == 0"
          ><i class="iconfont icon-refresh"></i> 恢复状态</el-button
        >
        <el-button type="green" @click="downloadTpl"
          ><i class="iconfont icon-download"></i> 模板下载</el-button
        >
        <el-upload
          style="display: inline-block; margin: 0 10px"
          :action="config.baseApi + '/uploadFile/maintenanceDeviceImport'"
          accept=".xlsx"
          :show-file-list="false"
          :on-success="importSuccess"
          :on-error="importError"
          :data="importParams"
          :disabled="!activePartition || activePartition.id == 0"
          :headers="{ Authorization: 'Bearer ' + siteInfos.token }"
        >
          <el-button
            type="blue"
            :disabled="!activePartition || activePartition.id == 0"
            ><i class="iconfont icon-import-folder"></i> 导入</el-button
          >
        </el-upload>
        <el-button
          type="green"
          @click="createTask"
          :disabled="createTaskDisabled"
          ><i class="iconfont icon-publish"></i> 生成任务书</el-button
        >
        <el-button
          type="blue"
          @click="createAction"
          :disabled="!activePartition || activePartition.id == 0"
          ><i class="iconfont icon-add"></i>新增设备</el-button
        >
      </div>
      <el-table
        :data="dataList"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          :selectable="checkSelectTable"
        ></el-table-column>
        <el-table-column
          type="index"
          label="序号"
          width="90"
          :index="indexMethod"
        ></el-table-column>
        <el-table-column prop="name" label="设备名称"></el-table-column>
        <el-table-column
          prop="deviceTypeName"
          label="设备类型"
        ></el-table-column>
        <el-table-column label="检修状态">
          <template slot-scope="scope">
            {{ scope.row.state == 1 ? "已检测" : "未检测" }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <div class="nowrap">
              <el-button type="blue" @click="eidtAction(scope.row)"
                >编辑</el-button
              >
              <el-button
                type="red"
                @click="deleteAction(scope.row, scope.$index)"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="total > 0"
        class="text-right mt-20 mr-20"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="sizes, prev, pager, next, total, jumper"
        :page-sizes="[20, 50, 100, 500, 1000]"
        :total="total"
      >
      </el-pagination>
    </el-main>
    <!-- 新增start -->
    <el-dialog
      :title="newModalTitle"
      :visible.sync="newModalVisible"
      v-if="newModalVisible"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      destroy-on-close
      append-to-body
    >
      <create
        ref="create"
        :activePartition="activePartition"
        :activeData="activeData"
        :typeList="typeList"
        :businessId="businessId"
        @success="submitSuccessAction"
        @fail="adding = false"
        @submitting="adding = true"
        @cancel="newModalVisible = false"
        @getData="getData"
      >
      </create>
      <div slot="footer">
        <el-button type="cancel" @click="newModalVisible = false"
          >取消</el-button
        >
        <el-button type="primary" :loading="adding" @click="submitAction"
          >确定</el-button
        >
      </div>
    </el-dialog>
    <!-- 新增start -->
    <!-- 新增任务 start -->
    <el-dialog
      title="生成任务书"
      :visible.sync="newTaskModalVisible"
      v-if="newTaskModalVisible"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      destroy-on-close
      append-to-body
    >
      <taskCreate
        ref="taskCreate"
        :activePartition="activePartition"
        :selectedDevice="multipleSelection"
        :businessId="businessId"
        @success="submitTaskSuccessAction"
        @fail="adding = false"
        @submitting="adding = true"
        @cancel="newTaskModalVisible = false"
      >
      </taskCreate>
      <div slot="footer">
        <el-button type="cancel" @click="newModalVisible = false"
          >取消</el-button
        >
        <el-button type="primary" :loading="adding" @click="submitTaskAction"
          >确定</el-button
        >
      </div>
    </el-dialog>
    <!-- 新增任务 start -->
  </el-container>
</template>
<script>
import { mapState } from "vuex";
import partitionTree from "./PartitionTree.vue";
import create from "./DeviceCreate.vue";
import taskCreate from "./TaskCreate.vue";
export default {
  components: {
    partitionTree,
    create,
    taskCreate,
  },
  props: {
    winH: {
      //企业ID
      type: Number,
      default: 500,
    },
    businessId: {
      //企业ID
      type: String,
      default: "",
    },
  },
  data() {
    return {
      filterForm: {
        partitionId: "",
      },
      loading: false,
      total: 0,
      currentPage: 1,
      pageSize: 20,
      loading: false,
      dataList: [],
      multipleSelection: [],
      typeList: [],
      activePartition: null,
      activeData: null,
      newModalVisible: false,
      newModalTitle: "",
      adding: false,
      newTaskModalVisible: false,
      importParams: { businessId: "", partitionId: "" },
    };
  },
  computed: {
    ...mapState(["siteInfos"]),
    createTaskDisabled() {
      const max = this.dataList.length;
      const selectedNum = this.multipleSelection.length;
      return selectedNum < 1 || selectedNum < max * 0.08;
    },
  },
  created() {
    this.getDeviceType();
    this.importParams.businessId = this.businessId;
    this.importParams.token = this.siteInfos.token;
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    getDeviceType(cbk) {
      this.$get("/check/maintenance/maintenanceTypeList").then((res) => {
        this.typeList = res.data;
        cbk && cbk();
      });
    },
    getData(page) {
      this.loading = true;
      let params = Object.assign(
        {
          page: page,
          limit: this.pageSize,
          businessId: this.businessId,
        },
        this.filterForm
      );
      this.$get("/check/maintenance/deviceListPage", params).then(
        (res) => {
          this.loading = false;
          let data = res.data;
          this.currentPage = page;
          if (data.Items) {
            this.total = data.totalSize;
            this.dataList = data.Items.map((item) => {
              return item;
            });
          } else {
            this.total = 0;
            this.dataList = [];
          }
        },
        (err) => {
          this.loading = false;
          if (err.msg) {
            this.$message.error(err.msg);
          }
        }
      );
    },
    handleCurrentChange(page) {
      this.getData(page);
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.getData(1);
    },
    indexMethod(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1;
    },
    searchAction() {
      this.getData(1);
    },
    resetAction() {
      this.filterForm = {};
      this.seatList = [];
    },
    partitionClickAction(item) {
      this.activePartition = item;
      this.filterForm.partitionId = item.id;
      this.importParams.partitionId = item.id;
      this.getData(1);
    },
    createAction(item) {
      this.activeData = null;
      this.newModalTitle = "新增设备";
      this.newModalVisible = true;
    },
    eidtAction(item) {
      this.activeData = item;
      this.newModalTitle = "编辑设备";
      this.newModalVisible = true;
    },
    submitAction() {
      this.$refs.create.submitAction();
    },
    submitSuccessAction() {
      this.getData(this.currentPage);
      this.adding = false;
      this.newModalVisible = false;
    },
    deleteAction(item) {
      this.showConfirm("确定删除该设备吗？", () => {
        this.deleting = true;
        this.$post("/check/maintenance/deviceDel", {
          id: item.id,
        }).then(
          (res) => {
            this.deleting = false;
            this.$message.success("删除成功");
            this.getData(this.currentPage);
          },
          (err) => {
            this.deleting = false;
            this.$message.error(err.msg);
          }
        );
      });
    },
    createTask() {
      this.newTaskModalVisible = true;
    },
    submitTaskSuccessAction() {
      this.getData(this.currentPage);
      this.adding = false;
      this.newTaskModalVisible = false;
    },
    submitTaskAction() {
      this.$refs.taskCreate.submitAction();
    },
    downloadTpl() {
      window.open(this.config.baseApi + "/check/maintenance/getTemplate");
    },
    importSuccess(res, file) {
      let resData = res.data;
      if (res.code == 0) {
        if (resData) {
          resData = JSON.parse(resData);
          if (resData.webPath) {
            window.open(
              this.config.baseApi +
                "/uploadFile/downloadExcel?fileName=" +
                resData.webPath
            );
          } else {
            this.$message.success("导入成功");
            this.getData(this.currentPage);
          }
        }
      } else {
        if (resData) {
          resData = JSON.parse(resData);
          if (resData.webPath) {
            window.open(
              this.config.baseApi +
                "/uploadFile/downloadExcel?fileName=" +
                resData.webPath
            );
          }
        } else {
          this.$message.error(res.msg);
        }
      }
    },
    importError(err, file, fileList) {
      // window.open(this.config.baseApi + '/uploadFile/downloadExcel')
    },
    // 恢复状态
    recoveryStatus() {
      this.showConfirm("确定恢复所有状态吗？", () => {
        this.$post("/check/maintenance/updateDeviceState", {
          partitionId: this.activePartition.id,
        })
          .then(() => {
            this.getData(1);
            this.$message.success("操作成功");
          })
          .catch(() => {
            this.$message.error("操作失败");
          });
      });
    },
    checkSelectTable(row) {
      return row.state == 2;
      //   返回为true可以选中
    },
  },
};
</script>
